<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;

//use Encore\Admin\Admin;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Controllers\Dashboard;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Echarts\Echarts;
use Encore\Admin\Widgets\InfoBox;
use Ixudra\Curl\Facades\Curl;
use DB;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index(Request $request, Content $content)
    {
    	//$data = $request->session()->all();
    	//print_r($data);exit;
    	$sId = Admin::user()->sId;
    	if ($sId == 0){
    		$content->header('巴谱门店管理系统');
        	$content->body('');
        	return $content;
    	}
    	$sId = Admin::user()->sId;
    	if ($sId == 0){
    		$content->header('巴谱门店管理系统');
    		$content->description('超级管理员');
        	return $content;
    	}

    	$sInfo = DB::table('store')->where("sId", $sId)->first();

    	$memberNum = $this->common->getAllMemberNum($sId);

    	$inventoryInfo = $this->common->getInventoryInfo($sId);

      	$content->row(function ($row) use($sInfo, $memberNum, $inventoryInfo) {
      		$host = config('admin.dataApiHost');
      		///////////////////获取统计信息///////////////////////////
			$statsUrl = $host."/statistics/getObjInfo";
			$statsData = array();
			$statsData['scKey'] = $sInfo->sId;
			$statsData['sdDay'] = date("Y-m-d");
			$statsData['sdObjId'] = $sInfo->sCode;

//			$dayStart = date("Y-m-d 00:00:00");
//            $dayEnd = date("Y-m-d 23:59:59");
//            $MonthStart = date("Y-m-01 00:00:00");
//            $MonthEnd = date('Y-m-d 23:59:59', strtotime("$MonthStart +1 month -1 day"));
            $today = date('Y-m-d', time());
            $month = date('Y-m', time());

			$data = Curl::to($statsUrl)->withData($statsData)->get();
			$data = json_decode($data, true);
			$statusItems = $data['data'];
			// 统计名单：           流水                                成本             利润                    新增会员                    办卡数                  耗卡数                  办卡收入                会员卡充值            会员卡消费                   会员卡充值人数
			$statsArray = ['flowAccount', 'cost', 'profit', 'newMember', 'timeCard', 'useCard', 'cardFlow', 'recharge', 'consumption', 'rechargeNum'];
			// 统计数据初始化
			$statusResult = array();
			foreach($statsArray as $statsName){
				$statusResult[$statsName.'Day'] = 0;
				$statusResult[$statsName.'Month'] = 0;
			}
			// 统计数据赋值
			if($statusItems) {
                foreach ($statusItems as $statusItem) {
                    foreach ($statusResult as $key => $value) {
                        if (isset($statusItem['sdName'])) {
                            if ($statusItem['sdName'] . 'Day' == $key) {
                                $statusResult[$key] = $statusItem['sdValue'];
                            }
                        } else if (isset($statusItem['smName'])) {
                            if ($statusItem['smName'] . 'Month' == $key) {
                                $statusResult[$key] = $statusItem['smValue'];
                            }
                        }
                    }
                }
            }

			$accountUrl = $host."/wallet/getAccountInfo?wcusKey={$sInfo->sId}&uId={$sInfo->sCode}";
			$data = Curl::to($accountUrl)->get();

			try {
			     $data = json_decode($data, true);
			     if ($data['code'] == 0){
			     	$accountMoney = $data['msg'];
			     }else{
			     	$accountMoney = $data['data']['waMoney'];
			     }
			} catch (Exception $e) {
			     $accountMoney = '获取账户信息错误！';
			}


      		$today = date('Y-m-d', time());
      		$sId = $sInfo->sId;
      		$sCode = $sInfo->sCode;

      		/*
      		 * 所有颜色
      		 * red, yellow, aqua, blue, light-blue, green, navy, teal, olive, lime,
      		 * orange, fuchsia, purple, maroon, black, red-active, yellow-active,
      		 * aqua-active, blue-active, light-blue-active, green-active, navy-active,
      		 * teal-active, olive-active, lime-active, orange-active, fuchsia-active,
      		 * purple-active, maroon-active, black-active
      		 */
		    $row->column(3, new InfoBox('今日流水', 'users', 'red', "admin/stats/getDayAccount?sId={$sId}&date={$today}&objId={$sCode}", $statusResult['flowAccountDay'])); // 标题，图标，颜色，链接，数量
            $row->column(3, new InfoBox('今日消耗成本', 'shopping-cart', 'red', "admin/stats/getDayAccount?sId={$sId}&date={$today}&objId={$sCode}", $statusResult['costDay']));
            $row->column(3, new InfoBox('今日赚取利润', 'book', 'red', "admin/stats/getDayAccount?sId={$sId}&date={$today}&objId={$sCode}", $statusResult['profitDay']));
            $row->column(3, new InfoBox('&nbsp;', '&nbsp;', '&nbsp;', false, '&nbsp;'));


            $row->column(3, new InfoBox('今日办卡项数', 'users', 'yellow', "admin/stats/getDayCard?sId={$sId}&date={$today}", $statusResult['timeCardDay'])); // 标题，图标，颜色，链接，数量
            $row->column(3, new InfoBox('今日办卡入账', 'users', 'yellow', "admin/stats/getDayCard?sId={$sId}&date={$today}", $statusResult['cardFlowDay'])); // 标题，图标，颜色，链接，数量
            $row->column(3, new InfoBox('今日消耗卡项次数', 'shopping-cart', 'yellow', "admin/stats/getDayUseCard?sId={$sId}&date={$today}", $statusResult['useCardDay']));
            $row->column(3, new InfoBox('&nbsp;', '&nbsp;', '&nbsp;', false, '&nbsp;'));

            $row->column(3, new InfoBox('今日新增会员', 'users', 'light-blue', "admin/stats/getDayAddMember?sId={$sId}&date={$today}", $statusResult['newMemberDay']));
            $row->column(3, new InfoBox('今日会员卡充值', 'users', 'light-blue', "admin/stats/getDayRecharge?sId={$sId}&type=rechargeDay&objId={$sCode}", $statusResult['rechargeDay'])); // 标题，图标，颜色，链接，数量
            $row->column(3, new InfoBox('今日会员卡消费', 'shopping-cart', 'light-blue', "admin/stats/getDayRecharge?sId={$sId}&type=consumptionDay&objId={$sCode}", $statusResult['consumptionDay']));
            $row->column(3, new InfoBox('&nbsp;', '&nbsp;', '&nbsp;', false, '&nbsp;'));

            $row->column(3, new InfoBox('本月流水', 'users', 'red', "admin/stats/showCalendar?sId={$sId}&type=account&objId={$sCode}", $statusResult['flowAccountMonth'])); // 标题，图标，颜色，链接，数量
            $row->column(3, new InfoBox('本月消耗成本', 'shopping-cart', 'red', "admin/stats/showCalendar?sId={$sId}&type=account&objId={$sCode}", $statusResult['costMonth']));
            $row->column(3, new InfoBox('本月赚取利润', 'book', 'red', "admin/stats/showCalendar?sId={$sId}&type=account&objId={$sCode}", $statusResult['profitMonth']));
            $row->column(3, new InfoBox('&nbsp;', '&nbsp;', '&nbsp;', false, '&nbsp;'));

            $row->column(3, new InfoBox('本月办卡项数', 'users', 'yellow', false, $statusResult['timeCardDay'])); // 标题，图标，颜色，链接，数量
            $row->column(3, new InfoBox('本月办卡入账', 'users', 'yellow', false, $statusResult['cardFlowMonth'])); // 标题，图标，颜色，链接，数量
            $row->column(3, new InfoBox('本月消耗卡项次数', 'shopping-cart', 'yellow', false, $statusResult['useCardDay']));
            $row->column(3, new InfoBox('&nbsp;', '&nbsp;', '&nbsp;', false, '&nbsp;'));

			$row->column(3, new InfoBox('本月新增会员', 'users', 'light-blue', false, $statusResult['newMemberMonth']));
            $row->column(3, new InfoBox('本月会员卡充值', 'users', 'light-blue', false, $statusResult['rechargeMonth'])); // 标题，图标，颜色，链接，数量
            $row->column(3, new InfoBox('本月会员卡消费', 'shopping-cart', 'light-blue', false, $statusResult['consumptionMonth']));
            $row->column(3, new InfoBox('&nbsp;', '&nbsp;', '&nbsp;', false, '&nbsp;'));

            $row->column(3, new InfoBox('现库存可产生最大流水', 'book', 'purple', false, isset($inventoryInfo['maxSale'])?$inventoryInfo['maxSale']:$inventoryInfo));
            $row->column(3, new InfoBox('现库存成本', 'book', 'purple', false, isset($inventoryInfo['goodsCost'])?$inventoryInfo['goodsCost']:$inventoryInfo));
			$row->column(3, new InfoBox('现库存批次数', 'users', 'purple', false, isset($inventoryInfo['batchNum'])?$inventoryInfo['batchNum']:$inventoryInfo));
			$row->column(3, new InfoBox('&nbsp;', '&nbsp;', '&nbsp;', false, '&nbsp;'));

            $row->column(3, new InfoBox('账户余额', 'book', 'olive', false, $accountMoney));
            $row->column(3, new InfoBox('会员总数', 'shopping-cart', 'olive', false, $memberNum));
            $row->column(3, new InfoBox('现库存总数', 'shopping-cart', 'olive', false, isset($inventoryInfo['goodsNum'])?$inventoryInfo['goodsNum']:$inventoryInfo));
            $row->column(3, new InfoBox('&nbsp;', '&nbsp;', '&nbsp;', false, '&nbsp;'));

            $row->column(3, new InfoBox('&nbsp;', '&nbsp;', '&nbsp;', false, '&nbsp;'));
            $row->column(3, new InfoBox('&nbsp;', '&nbsp;', '&nbsp;', false, '&nbsp;'));

        });

	    $content->header('巴谱门店管理系统');
        //$host = config('admin.dataApiHost');
        //$url = $host."/store/getAdminShopList?page=1&limit=50&username=".Admin::user()->username;

        		//$response = Curl::to($url)->get();
        		//$data = $this->handelApiData($response);


        $content->description($sInfo->sName.'');

//		$auCode = Admin::user()->auCode;
//
//		Admin::js('https://cdn.bootcss.com/jquery.qrcode/1.0/jquery.qrcode.min.js');
//		$id = Admin::user()->id;
//
//$script = <<<EOT
//var qrcode= $("#qr{$id}").qrcode({
//  render: "canvas", //table方式
//  width: 200, //宽度
//  height:200, //高度
//  text: "{$auCode}" //任意内容
//});
//
//
//$("#qr{$id}").click(function(){
//
//	var canvas=qrcode.find('canvas').get(0);
//	//如果有循环,此句必不可少 qrcode.find('canvas').remove();
//	var imgUrl = canvas.toDataURL('image/jpg');
//
//	if (window.navigator.msSaveOrOpenBlob) {
//	 var bstr = atob(imgUrl.split(',')[1])
//	 var n = bstr.length
//	 var u8arr = new Uint8Array(n)
//	 while (n--) {
//	  u8arr[n] = bstr.charCodeAt(n)
//	 }
//	 var blob = new Blob([u8arr])
//	 window.navigator.msSaveOrOpenBlob(blob, 'chart-download' + '.' + 'png')
//	} else {
//	 // 这里就按照chrome等新版浏览器来处理
//	 const a = document.createElement('a')
//	 a.href = imgUrl
//	 a.setAttribute('download', 'chart-download')
//	 a.click()
//	}
//});
//
//
//EOT;
//		Admin::script($script);
//
//      $content->row(function ($row) {
//      	$htmlStr = '<div id="qr'.Admin::user()->id.'"></div>';
//          $row->column(4, $htmlStr); // 标题，图标，颜色，链接，数量
//      });

        return $content;
    }
}
